// src/services/billingService.ts
import {
  acknowledgePurchaseAndroid,
  endConnection,
  fetchProducts,
  finishTransaction,
  getAvailablePurchases,
  initConnection,
  Product,
  Purchase,
  PurchaseError,
  purchaseErrorListener,
  purchaseUpdatedListener,
  requestPurchase,
} from 'react-native-iap';
import { Platform } from 'react-native';
import api from './api';

const productIds =
  Platform.select({
    android: [
      'ai_tool_basic_monthly',
      'ai_tool_premium_monthly',
      'ai_tool_premium_yearly',
    ],
    ios: [
      'com.aitool.basic.monthly',
      'com.aitool.premium.monthly',
      'com.aitool.premium.yearly',
    ],
  }) || [];

interface SubscriptionInfo {
  plan: 'FREE' | 'BASIC' | 'PREMIUM';
  expiryTime?: string;
  autoRenew: boolean;
  platform: 'android' | 'ios';
}

class BillingService {
  private purchaseUpdateSubscription: any = null;
  private purchaseErrorSubscription: any = null;
  private isInitialized = false;

  // 初始化
  async initialize(): Promise<void> {
    if (this.isInitialized) return;

    try {
      await initConnection();

      // 设置购买监听器
      this.purchaseUpdateSubscription = purchaseUpdatedListener(
        async (purchase: Purchase) => {
          await this.handlePurchaseUpdate(purchase);
        }
      );

      this.purchaseErrorSubscription = purchaseErrorListener(
        (error: PurchaseError) => {
          console.error('Purchase error:', error);
        }
      );

      this.isInitialized = true;
    } catch (error) {
      console.error('Billing initialization error:', error);
      throw error;
    }
  }

  // 获取订阅产品
  async getSubscriptions(): Promise<Product[]> {
    await this.initialize();

    try {
      return await fetchProducts({ skus: productIds });
    } catch (error) {
      console.error('Get products error:', error);
      return [];
    }
  }

  // 购买订阅
  async purchaseSubscription(productId: string): Promise<void> {
    await this.initialize();

    try {
      await requestPurchase({
        request: {
          android: {
            skus: [productId],
          },
        },
        type: 'subs',
      });
    } catch (error: any) {
      if (error.code === 'E_USER_CANCELLED') {
        throw new Error('用户取消购买');
      }
      throw error;
    }
  }

  // 处理购买更新
  private async handlePurchaseUpdate(purchase: Purchase): Promise<void> {
    const receipt = purchase;

    if (!receipt) {
      return;
    }

    try {
      // 验证购买
      const isValid = await this.validatePurchase(purchase);

      if (isValid) {
        // 完成交易
        await finishTransaction({ purchase });

        // Android需要确认购买
        if (Platform.OS === 'android' && purchase.purchaseToken) {
          await acknowledgePurchaseAndroid(purchase.purchaseToken);
        }

        // 通知服务器
        await this.notifyServer(purchase);
      }
    } catch (error) {
      console.error('Handle purchase error:', error);
    }
  }

  // 验证购买
  private async validatePurchase(purchase: Purchase): Promise<boolean> {
    try {
      const response = await api.post('/api/subscription/validate', {
        platform: Platform.OS,
        productId: purchase.productId,
        purchaseToken: purchase.purchaseToken,
        orderId: purchase.id,
      });

      return response.data.valid;
    } catch (error) {
      console.error('Validation error:', error);
      return false;
    }
  }

  // 通知服务器
  private async notifyServer(purchase: Purchase): Promise<void> {
    try {
      const payload: any = {
        platform: Platform.OS,
        productId: purchase.productId,
        transactionId: purchase.id,
        transactionDate: purchase.transactionDate,
      };

      // 根据平台传递不同的凭证
      if (Platform.OS === 'ios' && 'transactionReceipt' in purchase) {
        payload.transactionReceipt = (purchase as any).transactionReceipt;
      } else if (Platform.OS === 'android' && 'purchaseToken' in purchase) {
        payload.purchaseToken = (purchase as any).purchaseToken;
      }

      await api.post('/api/subscription/notify', payload);

    } catch (error) {
      console.error('Notify server error:', error);
    }
  }

  // 恢复购买
  async restorePurchases(): Promise<Purchase[]> {
    await this.initialize();

    try {
      const purchases = await getAvailablePurchases();

      // 验证每个购买
      for (const purchase of purchases) {
        await this.handlePurchaseUpdate(purchase);
      }

      return purchases;
    } catch (error) {
      console.error('Restore purchases error:', error);
      throw error;
    }
  }

  // 获取订阅状态
  async getSubscriptionStatus(): Promise<SubscriptionInfo> {
    try {
      const response = await api.get<SubscriptionInfo>('/api/subscription/status');
      return response.data;
    } catch (error) {
      console.error('Get subscription status error:', error);
      return {
        plan: 'FREE',
        autoRenew: false,
        platform: Platform.OS as 'android' | 'ios',
      };
    }
  }

  // 取消订阅
  async cancelSubscription(): Promise<void> {
    try {
      await api.post('/api/subscription/cancel');
    } catch (error) {
      console.error('Cancel subscription error:', error);
      throw error;
    }
  }

  // 清理
  cleanup(): void {
    if (this.purchaseUpdateSubscription) {
      this.purchaseUpdateSubscription.remove();
      this.purchaseUpdateSubscription = null;
    }

    if (this.purchaseErrorSubscription) {
      this.purchaseErrorSubscription.remove();
      this.purchaseErrorSubscription = null;
    }

    if (this.isInitialized) {
      endConnection();
      this.isInitialized = false;
    }
  }
}

export default new BillingService();